package com.zhsource.controller;


import com.zhsource.utils.R;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * minio控制器
 */
@RestController
@RequestMapping("/minio")
public class MinIoController {

    private static final String ACCESSKEY = "minioadmin";
    private static final String SECREKEY = "minioadmin123?";
    private static final String ADDRESS = "http://115.159.88.63:9090";
    private static final String BUCKETNAME = "java-very-good-0712";

    /**
     * 上传文件
     * @param file 要上传的文件的复杂对象
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            //处理文件名
            String oName = file.getOriginalFilename();
            String fileName = System.currentTimeMillis()+oName.substring(oName.lastIndexOf("."));

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName)	//文件名
                .bucket(MinIoController.BUCKETNAME)  //存储目录名
                .stream(file.getInputStream(), file.getSize(), -1).build(); //文件流，以及大小，-1代表不分片

            //执行上传
            minioClient.putObject(putObjectArgs);
            return R.ok("上传成功！", fileName);

        } catch (Exception e) {
            return R.fail("上传失败！");
        }
    }

    /**
     * 删除文件
     * @param name 要删除的文件的名称
     * @return
     */
    @DeleteMapping("/{name}")
    public R<String> delete(@PathVariable("name")String name) {
        try {
            // 构建一个Minio客户端
            MinioClient minioClient = MinioClient.builder()
                //创建容器时指定的账号
                .credentials(MinIoController.ACCESSKEY, MinIoController.SECREKEY)
                //上传地址
                .endpoint(MinIoController.ADDRESS).build();

            minioClient.removeObject(MinIoController.BUCKETNAME, name);
            return R.ok("删除成功！");
        } catch (Exception e) {
            return R.fail("删除失败！");
        }
    }
}